<?php
/*
 * @Author: lokei
 * @Date: 2022-08-20 17:03:15
 * @LastEditors: lokei
 * @LastEditTime: 2022-08-22 22:00:05
 * @Description: 
 */

namespace App\Http\Controllers\Scrm\Department;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Scrm\Qiwei\Common;
use App\Models\Scrm\Department\DepartmentModel;
use Illuminate\Http\Request;

use GuzzleHttp;

class DepartmentController extends Controller
{
    public function list()
    {
        $departments_list = DepartmentModel::get();
        $res = ResultTool::success();
        $res['data']['items'] = $departments_list;
        return $res;
    }

    public function update(Request $request) {
        $http = new GuzzleHttp\Client;
        $department = DepartmentModel::where('id', '=', $request->input('id'))->first();
        $params = [
            'id' => $department->qw_id,
            'name' => $request->input('name')
        ];
        $response = $http->POST('https://qyapi.weixin.qq.com/cgi-bin/department/update', [
            'query' => [
                'access_token' => Common::getAccessToken()
            ],
            'json' => $params
        ]);
        $result = json_decode($response->getBody(), true);
        if (array_key_exists('errcode', $result) && $result['errcode'] != 0) {
            $res = ResultTool::fail();
            $res['errorCode'] = $result['errcode'];
            $res['errorMsg'] = $result['errmsg'];
            return $res;
        } else {
            $department->name = $request->input('name');
            $department->save();
        }
        return ResultTool::success();
    }
}
